package com.jetpackframework.webview;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;

import com.jetpackframework.ContextUtil;
import com.jetpackframework.IMainProcessToWebViewInsterface;
import com.jetpackframework.IWebViewToMainProcessInsterface;

import org.json.JSONObject;

public class WebViewCommandDispatcher implements ServiceConnection {
    private IWebViewToMainProcessInsterface wvtmp;
    private static WebViewCommandDispatcher dispatcher;
    public static synchronized WebViewCommandDispatcher getInstance() {
        if (dispatcher == null){
            dispatcher = new WebViewCommandDispatcher();
        }
        return dispatcher;
    }

    public void execCommand(WebViewCommand command, IMainProcessToWebViewInsterface mainProcessToWebViewInsterface) {
        if (wvtmp != null){
            try {
                JSONObject jsonObject = new JSONObject(command.param.toString());
                if (jsonObject.has("callbackname")){
                    command.callbackname = jsonObject.getString("callbackname");
                }
                wvtmp.handleWebViewCommand(command.name,command.param.toString(),command.callbackname,mainProcessToWebViewInsterface);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void initConnection() {
        Intent intent = new Intent(ContextUtil.get(),MainService.class);
        ContextUtil.get().bindService(intent,this, Context.BIND_AUTO_CREATE);
    }

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        wvtmp = IWebViewToMainProcessInsterface.Stub.asInterface(service);
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        wvtmp = null;
        initConnection();
    }
}
